package com.boe.web.action;

import com.boe.domain.User;
import com.boe.service.UserService;
import com.boe.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "UserServlet",urlPatterns = "/UserServlet")
public class UserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String methodName = request.getParameter("method");

        //登录
        if(methodName.equals("login")){
            login(request,response);
        }

        //注销
        if(methodName.equals("loginout")){
            loginout(request,response);
        }


    }

    /**
     *退出登录的方法
     * @param request
     * @param response
     */

    private void loginout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.将session对象销毁掉
        request.getSession().invalidate();

        //2.跳转到登录页面
        response.sendRedirect(request.getContextPath()+"/login.jsp");

    }


    /**
     * 登录的方法
     * @param request
     * @param response
     */
    private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //测试账户名和密码能否传到后台
        //System.out.println(username+"  "+password);
        //封装好数据
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        //处理数据
        UserService userService =new UserServiceImpl();
        User exitUser = userService.login(user);

        if(exitUser==null){
            request.setAttribute("msg","登录账户名或密码错误");
            request.getRequestDispatcher("/login.jsp").forward(request,response);

        }else {
            //用户信息保存
            request.getSession().setAttribute("exitUser",exitUser);
            //修改跳转链接，直接跳转到查询后的页面上
            response.sendRedirect(request.getContextPath()+"/CategoryServlet?method=findAll");
        }





    }
}
